package com.desire.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LittleDesire
 * @description
 * @date 2022-02-09 周三 15:42
 * @since 17
 */
public class _50_多线程下原子操作 {

    // 原子类  开启多个线程不会相互影响(不会出现脏读现象)
    AtomicInteger n = new AtomicInteger(50);

    public static void main(String[] args) throws Exception {
        var t = new _50_多线程下原子操作();
        new Thread(() -> {
            try {
                t.minus();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1").start();
        new Thread(() -> {
            try {
                t.minus();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();
        new Thread(() -> {
            try {
                t.minus();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T3").start();
        new Thread(() -> {
            try {
                t.minus();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T4").start();
    }

    public void minus() throws InterruptedException {
        while (true) {
            if (n.get() > 0) {
                // 自减 --
                n.decrementAndGet();
                System.out.printf("%s 售出一张票，剩余%d张票。 %n", Thread.currentThread().getName(), n.get());
            } else {
                break;
            }
            // 每1秒卖一张
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
